package com.yzs.controller.admin;

import com.yzs.common.bean.R;
import com.yzs.entity.Admin;
import com.yzs.service.IAdminService;
import com.yzs.service.Impl.AdminServiceImpl;
import com.yzs.utils.JwtUtil;
import com.yzs.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
//@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    IAdminService as = new AdminServiceImpl();
    @Autowired
    JwtUtil JwtUtil;

    /**
     * 登录用户
     * @param admin
     * @return
     */
    @RequestMapping("/login")
    public R login(@RequestBody Admin admin){
        admin.setPassword(MD5Util.GetMD5Code(admin.getPassword()));
        return as.login(admin.getUsername(),admin.getPassword());
    }

    /**
     * 查找用户信息
     * @param token
     * @return
     */
    @RequestMapping("/info")
    public R getAdminInfo(@RequestParam String token){
        Integer id = JwtUtil.verifyToken(token);
        if(id == -1 || id == null){
            return R.error("token error");
        }
        return as.getAdminById(id);
    }
    @RequestMapping("checkToken")
    public void checkToken(HttpServletRequest res){
        JwtUtil.verifyToken(res.getHeader("token"));
    }
//    @RequestMapping("/getAll")
//    public List<Admin> getAdmins(){
//        return mapper.selectList(null);
//    }
//

    /**
     * 注册用户
     * @param admin
     * @return
     */
    @RequestMapping(value = "/register")
    public R<String> saveAdmin(@RequestBody Admin admin){
        return as.register(admin);
    }

    @RequestMapping(value = "/loginOut")
    public R loginOut(@RequestBody String token){
        boolean isRemove = JwtUtil.removeToken(token);
        if (!isRemove){
            return R.error("用户状态过期，请重新登录！");
        }
        return R.ok("用户已退出！");
    }


}
